﻿using ActionFilterPlugin;
using ActionFilterPlugin.models;
using CommonEntity;
using CommonLibary;
using ConfigurationCommon;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using MySqlX.XDevAPI.Common;
using NetCore6WebAPITestOneEntity;
using NetCore6WebAPITestOneRequestEntity;
using NetCroe6WebAPITestOneResponse;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace NetCroe6WebAPITestOneBusiness
{
  
    public class UserinfoBusiness:BaseBusiness
    {
        UserinfoResponse _userinfoResponse;
        ConfigurationScopeHelper _configurationScopeHelper;
        LoginHelper _loginHelper;

        public UserinfoBusiness(LoggerSingletonHelper loggerSingletonHelper, UserinfoResponse userinfoResponse, ConfigurationScopeHelper configurationScopeHelper, LoginHelper loginHelper) : base(loggerSingletonHelper)
        {
            _userinfoResponse = userinfoResponse;
            _configurationScopeHelper = configurationScopeHelper;
            _loginHelper = loginHelper;
        }

        public ViewModelBase GetUserModel(long userId) {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                vb.data = _userinfoResponse.GetUserModel(userId);
                vb.code = HttpStatusCode.OK;
                return vb;
            });
        }

        public ViewModelBase UserLogin(UserLoginViewModel userinfo)
        {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                userinfo.UserPwd = EncryptUtil.Get32MD5(userinfo.UserPwd);
                UserinfoModel rtUserinfo = _userinfoResponse.GetUserModel(userinfo);
                if (rtUserinfo == null || rtUserinfo.UserID <= 0)
                {
                    vb.code = HttpStatusCode.NotAcceptable;
                }
                else
                {
                    

                    vb.code = HttpStatusCode.OK;


                    #region 获取业务线获取,这块
                    var expires = DateTime.Now.AddHours(16);
                    string[] openLines = new string[] {
                        _configurationScopeHelper.GetConfigString("openline:swagger"),
                        _configurationScopeHelper.GetConfigString("openline:androidappkey")
                    };
                    if (!openLines.Contains(userinfo.OpenLine))
                    {
                        vb.code = HttpStatusCode.NotAcceptable;
                        vb.message = "参数openline有误";
                        return vb;
                    }
                    #endregion

                    vb.data
                     = _loginHelper.UserLogin<UserLoginModel>(new UserLoginModel()
                     {
                         UserId = rtUserinfo.UserID,
                         UserName = rtUserinfo.UserName
                     }, userinfo.OpenLine);
                    //vb.data = GetBaseToken(rtUserinfo, userinfo.OpenLine);
                }

                return vb;
            });
        }


        public ViewModelBase UserSwaggerLogin(UserLoginViewModel userinfo)
        {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                userinfo.UserPwd = EncryptUtil.Get32MD5(userinfo.UserPwd);
                UserinfoModel rtUserinfo = _userinfoResponse.GetUserModel(userinfo);
                if (rtUserinfo == null || rtUserinfo.UserID <= 0)
                {
                    vb.code = HttpStatusCode.NotAcceptable;
                }
                else
                {
                    vb.code = HttpStatusCode.OK;
                    var expires = DateTime.Now.AddHours(16);

                    vb.data=_loginHelper.UserSwaggerLogin(new UserLoginModel()
                    {
                        UserId = rtUserinfo.UserID,
                        UserName = rtUserinfo.UserName
                    });
                    ////string baseToken = GetBaseToken(rtUserinfo, userinfo.OpenLine);


                    //string swaggerKey = _configurationScopeHelper.GetConfigString("JwtAuthorize:PublicSecret");

                    //LoginModel _loginModel = new LoginModel()
                    //{
                    //    Token = baseToken,
                    //    dt = DateTime.Now.AddHours(1),
                    //    SourceKey = userinfo.OpenLine
                    //};


                    //vb.data = SecurityHelper.Encrypt(JsonConvert.SerializeObject(_loginModel), swaggerKey);
                }

                return vb;
            });
        }

        //protected string GetBaseToken(UserinfoModel userinfo,string openLine) {
        //    #region 获取业务线获取,这块
        //    var expires = DateTime.Now.AddHours(16);
        //    #endregion

        //    var LoginAuthModel = new LoginAuthModel[]
        //    {
        //             new LoginAuthModel(LoginAuthEnum.UserInfo,Newtonsoft.Json.JsonConvert.SerializeObject(new {
        //                 userinfo.UserName,
        //                 userinfo.UserID
        //             })),
        //             new LoginAuthModel(LoginAuthEnum.Expires,expires.ToString()),
        //             new LoginAuthModel(LoginAuthEnum.SourceFromKey,openLine)
        //    };
        //    return SecurityHelper.Encrypt(JsonConvert.SerializeObject(LoginAuthModel), _configurationScopeHelper.GetConfigString("JwtAuthorize:BaseSecret")) ;
        //}

        /// <summary>
        /// jwt中间件自带的token生成
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ViewModelBase MicsoftAuthExp(string username,string pwd) {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                List<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, "1"));
                claims.Add(new Claim(ClaimTypes.Name, username));
                string baseSecret = _configurationScopeHelper.GetConfigString("JWT:SecKey");

                SymmetricSecurityKey seckey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(baseSecret));
                var credential = new SigningCredentials(seckey, SecurityAlgorithms.HmacSha256Signature);


                var jwttoken = new JwtSecurityToken(claims: claims, expires: DateTime.Now.AddMinutes(11), signingCredentials: credential);
                vb.data = new JwtSecurityTokenHandler().WriteToken(jwttoken);
                vb.code = HttpStatusCode.OK;
                return vb;
            });
        }

        /// <summary>
        /// 校验jwt加密的token
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ViewModelBase CheckMicsoftAuthExp(string jwt)
        {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                string secKey = _configurationScopeHelper.GetConfigString("JWT:SecKey");
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                TokenValidationParameters valParam = new TokenValidationParameters();
                var sercurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secKey));
                valParam.IssuerSigningKey= sercurityKey;
                valParam.ValidateIssuer = false;
                valParam.ValidateAudience = false;
                ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwt, valParam, out SecurityToken secToken);
                var claim = claimsPrincipal.Claims.FirstOrDefault();
                vb.data = new { 
                    claim.Type,
                    claim.Value
                };
                vb.code = HttpStatusCode.OK;
                return vb;
            });
        }


        public ViewModelBase GetUsers(GetUsersRequestViewModel p)
        {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                p.PageIndex = p.PageIndex <= 0 ? 1 : p.PageIndex;
                p.PageSize = p.PageSize <= 0 ? 20 : p.PageSize;
                vb.data = _userinfoResponse.GetUsers(p.PageIndex,p.PageSize);
                vb.code = HttpStatusCode.OK;
                return vb;
            });
        }

        public ViewModelBase InserUserinfo(InserUserinfoViewModel userinfo)
        {
            return DoFunc<ViewModelBase>(() =>
            {
                ViewModelBase vb = new ViewModelBase();
                userinfo.UserPwd=EncryptUtil.Get32MD5(userinfo.UserPwd);
                UserinfoModel u = toObject<UserinfoModel>(userinfo);
                u.IsValid = 1;
                vb.data = _userinfoResponse.InserUserinfo(u);
                vb.code = HttpStatusCode.OK;
                return vb;
            });
        }
    }
}
